package com.zhijian.wharf.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.poi.excel.ExcelReader;
import cn.hutool.poi.excel.ExcelUtil;
import com.beust.jcommander.internal.Lists;
import com.zhijian.BusinessException;
import com.zhijian.response.enums.ResponseCodeEnum;
import com.zhijian.util.AssertUtil;
import com.zhijian.util.page.Page;
import com.zhijian.wharf.dao.VideoDeviceMapper;
import com.zhijian.wharf.entity.dto.VideoDeviceImportDto;
import com.zhijian.wharf.entity.po.Area;
import com.zhijian.wharf.entity.po.VideoDevice;
import com.zhijian.wharf.entity.vo.request.VideoDeviceSaveOrUpdateVo;
import com.zhijian.wharf.entity.vo.request.VideoDeviceSearchVo;
import com.zhijian.wharf.entity.vo.response.VideoDeviceVo;
import com.zhijian.wharf.service.AreaService;
import com.zhijian.wharf.service.VideoDeviceService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.io.InputStream;
import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 视频设备业务处理层
 *
 * @author auto
 * @version: 1.0
 * @date 2024-07-10 13:59:25
 */
@Slf4j
@Service
public class VideoDeviceServiceImpl implements VideoDeviceService {

    @Autowired
    private VideoDeviceMapper mapper;

    @Autowired
    private AreaService areaService;

    @Override
    public VideoDevice selectById(Long id) {
        return mapper.selectByPrimaryKey(id);
    }

    @Override
    public VideoDeviceVo selectVoById(Long id) {
        return mapper.selectVoById(id);
    }

    @Override
    public void deleteById(Long id) {
        mapper.deleteByPrimaryKey(id);
    }

    @Override
    public void deleteByIdList(List<Long> idList) {
        if (CollectionUtil.isEmpty(idList)) {
            return;
        }
        mapper.deleteByIdList(idList);
    }

    @Override
    public Long insert(VideoDevice videoDevice) {
        Date now = new Date();
        videoDevice.setCreateTime(now);
        videoDevice.setUpdateTime(now);
        return mapper.insert(videoDevice) > 0 ? videoDevice.getId() : 0L;
    }

    @Override
    public Long insertSelective(VideoDevice videoDevice) {
        Date now = new Date();
        videoDevice.setCreateTime(now);
        videoDevice.setUpdateTime(now);
        return mapper.insertSelective(videoDevice) > 0 ? videoDevice.getId() : 0L;
    }

    @Override
    public boolean update(VideoDevice videoDevice) {
        Date now = new Date();
        videoDevice.setUpdateTime(now);
        return mapper.updateByPrimaryKey(videoDevice) != 0;
    }

    @Override
    public boolean updateByPrimaryKeySelective(VideoDevice record) {
        Date now = new Date();
        record.setUpdateTime(now);
        return mapper.updateByPrimaryKeySelective(record) != 0;
    }

    @Override
    public boolean save(VideoDeviceSaveOrUpdateVo saveOrUpdateVo) {
        Area area = areaService.selectById(saveOrUpdateVo.getAreaId());
        AssertUtil.notNull(area, "所属区域不存在或者已被删除");
        VideoDevice videoDevice = new VideoDevice();
        BeanUtils.copyProperties(saveOrUpdateVo, videoDevice);
        return this.insert(videoDevice) != 0;
    }

    @Override
    public boolean modify(VideoDeviceSaveOrUpdateVo saveOrUpdateVo) {
        VideoDevice old = this.selectById(saveOrUpdateVo.getId());
        AssertUtil.notNull(old, "此数据不存在或者已被删除");
        Area area = areaService.selectById(saveOrUpdateVo.getAreaId());
        AssertUtil.notNull(area, "所属区域不存在或者已被删除");
        VideoDevice videoDevice = new VideoDevice();
        BeanUtils.copyProperties(saveOrUpdateVo, videoDevice);
        return this.update(videoDevice);
    }

    @Override
    public VideoDeviceVo selectOne(VideoDeviceSearchVo videoDeviceSearchVo) {
        return mapper.selectOne(videoDeviceSearchVo);
    }

    @Override
    public Integer count(VideoDeviceSearchVo videoDeviceSearchVo) {
        return mapper.count(videoDeviceSearchVo);
    }

    @Override
    public List<VideoDeviceVo> selectList(VideoDeviceSearchVo videoDeviceSearchVo) {
        return mapper.selectList(videoDeviceSearchVo);
    }

    @Override
    public Page<VideoDeviceVo> selectPage(VideoDeviceSearchVo videoDeviceSearchVo) {
        AssertUtil.check(Objects.isNull(videoDeviceSearchVo.getPageNum()) || Objects.isNull(videoDeviceSearchVo.getPageSize()), "分页参数不能为空");
        //先直接查总数
        int count = count(videoDeviceSearchVo);
        //分页
        Page<VideoDeviceVo> page = new Page<>(true, count, videoDeviceSearchVo.getPageNum(), videoDeviceSearchVo.getPageSize());
        videoDeviceSearchVo.setStartIndex(page.getStartIndex());
        page.setPage(true);
        page.setTotalCount(count);
        List<VideoDeviceVo> responseVos = this.selectList(videoDeviceSearchVo);
        page.setData(responseVos);
        return page;
    }

    @Override
    public boolean insertBatch(List<VideoDevice> entities) {
        return CollectionUtil.isNotEmpty(entities) && mapper.insertBatch(entities) > 0;
    }

    @Override
    public void deleteByCondition(VideoDeviceSearchVo videoDeviceSearchVo) {
        //慎重用此方法！！
        mapper.deleteByCondition(videoDeviceSearchVo);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean importExcel(Long areaId, MultipartFile file) {
        InputStream inputStream = null;
        try {
            inputStream = file.getInputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        ExcelReader reader = ExcelUtil.getReader(inputStream)
                .addHeaderAlias("所属区域", "areaName")
                .addHeaderAlias("IP地址", "ipAddress")
                .addHeaderAlias("交换机口", "switchboardPort")
                .addHeaderAlias("配线架", "pxj")
                .addHeaderAlias("安装位置", "installLocation")
                .addHeaderAlias("密码", "password")
                .addHeaderAlias("子网掩码", "mask")
                .addHeaderAlias("网关", "gateway");
        List<VideoDeviceImportDto> examWarehouseImportDtoList = reader.readAll(VideoDeviceImportDto.class);
        AssertUtil.check(CollectionUtil.isEmpty(examWarehouseImportDtoList), "数据至少要有一行");
        List<VideoDevice> videoDeviceList = Lists.newLinkedList();
        Date now = new Date();
        for (int i = 0; i < examWarehouseImportDtoList.size(); i++) {
            VideoDeviceImportDto videoDeviceImportDto = examWarehouseImportDtoList.get(i);
            if (StringUtils.isBlank(videoDeviceImportDto.getIpAddress())
                    || StringUtils.isBlank(videoDeviceImportDto.getInstallLocation())) {
                throw new BusinessException(ResponseCodeEnum.FAILURE.code, String.format("第%s行有空数据，请重新填写", i + 1));
            }

            VideoDevice videoDevice = new VideoDevice();
            BeanUtils.copyProperties(videoDeviceImportDto, videoDevice);
            videoDevice.setAreaId(areaId);
            videoDevice.setCreateTime(now);
            videoDevice.setUpdateTime(now);
            videoDeviceList.add(videoDevice);
        }
        return this.insertBatch(videoDeviceList);
    }

}